import httprequest from "@/wxcomponents/luch-request/request.js";
import configIndex from "@/config/index";
import { customToast } from '@/utils/tips';
import  $Storage  from '@/utils/storage';
const uniRequest = new httprequest();
const Toast = customToast;
//设置全局配置
uniRequest.setConfig((config) => {
	config.baseUrl = configIndex.baseURL
	config.header = {
		...config.header,
		'content-type': 'application/x-www-form-urlencoded'
	}
	config.custom = {
		...config.custom,
		isShowLoading: true,
		isShowErrorMsg: true,
		isIntercept: true
	}
	return config
})

//请求后拦截
uniRequest.interceptor.response((response) => {
	Toast.clear();
	let num_code =  response.statusCode;
	if (num_code == 401) {
		// if(response.config.custom.isShowErrorMsg){
		// 	setTimeout(()=>{
		// 		Toast.fail(response.data.message);
		// 	},300)
		// }
			$Storage.clearStorage();
			
		if(response.config.custom.isIntercept){
			return Promise.reject(response.data);
		}
	    Promise.reject(response.data)
	}
	return response.data;
}, (response) => {
	console.log('请求中1'+ response)
	Toast.clear();
	let num_code =  response.statusCode;
	if (num_code == 403) {
		Toast.fail('暂无权限');
		// setTimeout(() => {
		// 	uni.navigateBack();
		// }, 1000)
	} else if (num_code == 401) {
		Toast.fail(response.data.message);
		$Storage.clearStorage();
		setTimeout(()=>{
			// getApp().login();
			uni.reLaunch({
			    url: '/pages/login/index'
			});
		},100)
	} else {
		setTimeout(()=>{
			Toast.fail('请求响应失败!');
		},500)
	}
})

 uniRequest.interceptor.request((config, cancel) => {
	if($Storage.getItem('accessToken')){
		config.header.Authentication = $Storage.getItem('accessToken');
	}
	if(config.custom.isShowLoading){
		Toast.loading(config.custom.loadingText || '加载中');
	}
    return config
  },()=>{
	 Toast.clear();
  })

module.exports = uniRequest;